<?php
// File: app/controllers/m_avoidance_words_controller.php.php
	class MAvoidanceWordsController extends AppController{
		
		var $name = 'MAvoidanceWord';
		var $helpers = array ('Html','Form','Javascript','Paginator','Csv');
		var $components = array('Session','Auth','RequestHandler');
		var $paginate = array();
		
		function beforeFilter() {
			parent::beforeFilter();
		}
		
		function index()
		{
			$this->set('title_for_layout','Avoidance Words List');
				
			$this->paginate=array
			(
				'limit' => 10,
				'order' => array('id' => 'desc'),
				'conditions' => array('invalid_flg' => '0')
			);
			$data = $this->paginate("MAvoidanceWord");
			$this->set("wordslist",$data);
		}
		

		function word_check()
		{
			//Read data from textarea on from
			if(isset($_POST['check']))
			{
				if($this->MAvoidanceWord->check_input_text()==true)
				{
					$script_content = $this->data['MAvoidanceWord']['textarea'];
					$word_data = $this->MAvoidanceWord->find('all',array(
						'fields' => 'avoidance_word,replace_word',
						'conditions' => array('invalid_flg' => '0')
					));
						
					foreach ($word_data as $word_item):
						$bad[] = $word_item['MAvoidanceWord']['avoidance_word'];
						$good[] = $word_item['MAvoidanceWord']['replace_word'];
					endforeach;
		
					$result = str_replace($bad, $good, $script_content);
					$this->set('view_result',$result);
				}
			}
			
			//Read data from txt file
			if(isset($_POST['upload']))
			{
				$script_content = file_get_contents($this->data['MAvoidanceWord']['file_name']['tmp_name']);
				//Set old script into textarea
				$this->data['MAvoidanceWord']['textarea']=$script_content;
				
				$word_data = $this->MAvoidanceWord->find('all',array(
					'fields' => 'avoidance_word,replace_word',
					'conditions' => array('invalid_flg' => '0')
				));
					
				foreach ($word_data as $word_item):
					$bad[] = $word_item['MAvoidanceWord']['avoidance_word'];
					$good[] = $word_item['MAvoidanceWord']['replace_word'];
				endforeach;
			
				$result = str_replace($bad, $good, $script_content);
				$this->set('view_result',$result);
			}
		}
		
		
		function add() {
			$this->set('title_for_layout','Add New Words');
			if (!empty($this->data)) {
				if(isset($_POST['create']))
				{
					//debug($this->data);
					if($this->MAvoidanceWord->check_add()==true){
						$this->MAvoidanceWord->set($this->data);
						//debug($this->data);
						foreach($this->data as $data)
						{
							if($this->MAvoidanceWord->saveAll($data))
							{
								$this->Session->setFlash('Your word(s) has been saved.');
								$this->redirect(array('action' => 'index'));
							}
							else
							{
								$this->MAvoidanceWord->rollback();
								$this->Session->setFlash('Can not add empty data');
							}
						}
					}
					else
					{
						$errors = $this->MAvoidanceWord->validationErrors;
					}
				}
			}
			
		}
		
		function edit($id = null) {
			$this->set('title_for_layout','Edit Words');
			if($this->MAvoidanceWord->check_add()==true){
				$this->MAvoidanceWord->id = $id;
				if (empty($this->data)) {
					$this->data = $this->MAvoidanceWord->read();
				} 
				else 
				{
					if ($this->MAvoidanceWord->save($this->data)) {
						$this->Session->setFlash('Your user has been updated.');
						$this->redirect(array('action' => 'index'));
					}
				}
			}
			else
			{
				$errors = $this->MAvoidanceWord->validationErrors;
			}
		}
		
		function delete($id) {
			$this->MAvoidanceWord->id = $id;
			if ($this->MAvoidanceWord->saveField('invalid_flg',1))
			{
				$this->Session->setFlash('The user with id: ' .$id . ' has been deleted.');
				$this->redirect(array('action' => 'index'));
			}
		}
		
		function search() {
			
	        // The page we will redirect to
	        $url['action'] = 'result';
	        foreach ($this->data as $k=>$v){ 
	            foreach ($v as $kk=>$vv){ 
	                $url[$k.'.'.$kk]=$vv; 
	            } 
	        }
	        // Redirect the user to the url
	        $this->redirect($url, null, true);
	    }
		
	    function result(){
	    	$this->set('title_for_layout','Search Words');
	    	$conditions = array();
	    	$data = array();
	    	if(!empty($this->passedArgs)){
	    		//Fillter avoidance_word
	    		if(isset($this->passedArgs['MAvoidanceWord.avoidance_word'])) {
	    			$avoidance_word = $this->passedArgs['MAvoidanceWord.avoidance_word'];
	    			$conditions[] = array(
	    						"OR" => array(
	    								'MAvoidanceWord.avoidance_word LIKE' => "%$avoidance_word%",
	    								'MAvoidanceWord.avoidance_word_yomi LIKE' => "%$avoidance_word%",
	    			)
	    			);
	    			$data['MAvoidanceWord']['avoidance_word'] = $avoidance_word;
	    		}
	    		//Fillter replace_word
	    		if(isset($this->passedArgs['MAvoidanceWord.replace_word'])) {
	    			$keywords = $this->passedArgs['MAvoidanceWord.replace_word'];
	    			$conditions[] = array(
	                        "OR" => array(
	                                    'MAvoidanceWord.replace_word LIKE' => "%$keywords%",
	                                    'MAvoidanceWord.replace_word_yomi LIKE' => "%$keywords%" 
	    			)
	    			);
	    			$data['MAvoidanceWord']['replace_word'] = $keywords;
	    		}
	    		//Limit and Order By
	    		$this->paginate= array(
	                    'limit' => 4,
	                    'order' => array('id' => 'desc'),
	    		);
	    
	    		$this->data = $data;
	    		$this->set("searchresults",$this->paginate("MAvoidanceWord",$conditions));
	    	}
	    }
		
	    function detail($id=null)
	    {
	    	$this->set('title_for_layout','Word Details');
	    	$this->MAvoidanceWord->id = $id;
	    	$this->set('m_avoidance_words', $this->MAvoidanceWord->read());
	    		
	    }
	    
	    function csv_export() {
	    	$this->set('title_for_layout','Export Words List');
	    	Configure::write('debug',0);
	    	$this->layout=false;
	    	$filename = 'Wordlist_'.date('YmdHis');//DO NOT change this, the validation in Import will be error 
	    	$th=array('id','avoidance_word','avoidance_word_yomi','replace_word','replace_word_yomi','creator','create_time','updator','update_time','invalid_flg');
	    	$Th_name=array('ID','Avoidance Words','Avoidance Words Yomi','Replace Word','Replace Word Yomi','Creator','Create Time','Updator','Update Time','Invalid Flag');
	    	$td=$this->MAvoidanceWord->find('all', array('fields'=>$th));
   	    	$this->set(compact('filename','Th_name','td'));
	    }
	    
	    function csv_import(){
	    	$this->set('title_for_layout','Input Words List');
	    	//Get current username.
	    	$get_author_infor = $this->Auth->user();
	    	$author=$get_author_infor['MUser']['user_name'];
	    	
	    	if (!empty($this->data)) {
	    		$up_file = $this->data['MAvoidanceWord']['file_name']['tmp_name'];
	    		$fileName = TMP.'/csv/'.$this->data['MAvoidanceWord']['file_name']['name'];
	    		if (is_uploaded_file($up_file)){
	    			move_uploaded_file($up_file, $fileName);
	    			try {
	    				$csvData = file($fileName, FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
	    				foreach($csvData as $key => $line){
	    					if($key != 0) {
	    						$record = split(",", $line);
	    						mb_language("Japanese");
	    						if(empty($record[5])){$creator=$author;}else{$creator=$record[5];}
	    						if(empty($record[6])){$create_time=date('Y-m-d H:i:s');}else{$create_time=$record[6];}
	    						if(empty($record[9])){$invalid_flg=0;}else{$invalid_flg=$record[9];}
	    						
	    						$data = array(
	                                'id' => $record[0],
	                                'avoidance_word' => mb_convert_encoding($record[1], "UTF-8", "SHIFT_JIS"),
	                                'avoidance_word_yomi' => mb_convert_encoding($record[2], "UTF-8", "SHIFT_JIS"),
	    							'replace_word' => mb_convert_encoding($record[3], "UTF-8", "SHIFT_JIS"),
	    							'replace_word_yomi' => mb_convert_encoding($record[4], "UTF-8", "SHIFT_JIS"),
	    							'creator' => mb_convert_encoding($creator, "UTF-8", "SHIFT_JIS"),
	    							'create_time' => $create_time,
	    							'updator' => mb_convert_encoding($record[7], "UTF-8", "SHIFT_JIS"),
	    							'update_time' => $record[8],
	    							'invalid_flg' => $invalid_flg
	    						);
	    						debug($data);
	    						$this->MAvoidanceWord->create($data);
	    						if ($this->MAvoidanceWord->save()) {
	    							$this->Session->setFlash('Import to me was successful');
	    							//$this->redirect(array('action' => 'index'));
	    						} else {
	    							$this->Session->setFlash('Import to me failed');
	    						}
	    					}
	    				}
	    			} catch(Exception $e) {
	    				$this->MAvoidanceWord->rollback();
	    			}
	    		}
	    	}
	    }

		
		
	}/*** End Class ***/

?>